package com.woniuxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniuxy.common.RedisKey;
import com.woniuxy.controller.form.AccountCheckForm;
import com.woniuxy.controller.form.AccountLoginForm;
import com.woniuxy.controller.form.AccountRegisterForm;
import com.woniuxy.controller.form.AccountUpdateForm;
import com.woniuxy.entity.Account;
import com.woniuxy.dao.AccountMapper;
import com.woniuxy.exception.account.AccountException;
import com.woniuxy.exception.account.AccountExceptionCode;
import com.woniuxy.exception.user.UserException;
import com.woniuxy.exception.user.UserExceptionCode;
import com.woniuxy.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.dto.AccountDto;
import com.woniuxy.util.RedisUtil;
import com.woniuxy.util.SMSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zz
 * @since 2023年06月13日
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 管理员/商家登录方法
     * @param accountLoginForm
     * @return
     */
    @Override
    public Account login(AccountLoginForm accountLoginForm) throws Exception {
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("phone",accountLoginForm.getPhone()).or().eq("email", accountLoginForm.getEmail());
        Account account = accountMapper.selectOne(accountQueryWrapper);
        if(account==null){
            throw new AccountException(AccountExceptionCode.ACCOUNT_NO_REGISTER);
        }
        if( accountLoginForm.getPhone()==null){ //邮箱密码登录
            if(!account.getPassword().equals(accountLoginForm.getPassword())){
                if(!redisUtil.exist(RedisKey.pwdCount(account.getEmail()))){
                    redisUtil.setString(RedisKey.pwdCount(account.getEmail()),"0",3600);
                }
                redisUtil.incr(RedisKey.pwdCount(account.getEmail()));
                throw new AccountException(AccountExceptionCode.ACCOUNT_PWD_NOT_MATCH);
            }
            String s = account.getEmail();
            if(redisUtil.exist(RedisKey.pwdCount(account.getEmail())) && Integer.parseInt(redisUtil.getString(RedisKey.pwdCount(s)))==5){
                throw new AccountException(AccountExceptionCode.ACCOUNT_PWD_MUCH_5);
            }
        }else{      //电话号码 验证码登录
            if(accountLoginForm.getCode()!=null && !(accountLoginForm.getCode().toString().equals(""))){
                Integer code =Integer.parseInt(redisUtil.getString(RedisKey.getSendlogCodeKey(account.getPhone())));
                if(!accountLoginForm.getCode().equals(code)){
                    throw new AccountException(AccountExceptionCode.ACCOUNT_CODE_NOT_MATCH);
                }
            }
        }
//        String s = account.getPhone().toString();
//        if(redisUtil.exist(RedisKey.pwdCount(account.getPhone().toString())) && Integer.parseInt(redisUtil.getString(RedisKey.pwdCount(s)))==5){
//            throw new AccountException(AccountExceptionCode.ACCOUNT_PWD_MUCH_5);
//        }
//        if(accountLoginForm.getCode()!=null && !(accountLoginForm.getCode().equals(""))){
//            Integer code =Integer.parseInt(redisUtil.getString(RedisKey.getSendlogCodeKey(account.getPhone())));
//            if(!accountLoginForm.getCode().equals(code)){
//                throw new AccountException(AccountExceptionCode.ACCOUNT_CODE_NOT_MATCH);
//            }
//        }
//        if(!account.getPassword().equals(accountLoginForm.getPassword())){
//            if(!redisUtil.exist(RedisKey.pwdCount(account.getPhone().toString()))){
//                redisUtil.setString(RedisKey.pwdCount(account.getPhone().toString()),"0",3600);
//            }
//            redisUtil.incr(RedisKey.pwdCount(account.getPhone().toString()));
//            throw new AccountException(AccountExceptionCode.ACCOUNT_PWD_NOT_MATCH);
//        }
        redisUtil.delete(RedisKey.getSendlogCodeKey(accountLoginForm.getPhone()));
        return account;
    }

    /**
     * 发送管理员/商家登录验证码
     * @param phone
     */
    @Override
    public void sendCode(String phone) throws Exception {
        //判断一分钟内是否已经发过
        String sendRegCodeInMinKey = RedisKey.getSendlogCodeInMinKey(phone);
        boolean exist = redisUtil.exist(sendRegCodeInMinKey);
        if(exist){
            throw new AccountException(AccountExceptionCode.ACCOUNT_CODE_USE_TOMUCH);
        }
        //判断一小时内是否已经第五次了
        if(redisUtil.exist(RedisKey.getSendlogCodeInHourKey(phone)) && Integer.parseInt(redisUtil.getString(RedisKey.getSendlogCodeInHourKey(phone)))==5){
            throw new AccountException(AccountExceptionCode.ACCOUNT_CODE_MUCH_5);
        }
//        String code = SMSUtil.send(phone);
        String code = "123321";
        Long phoneL = Long.valueOf(phone);
        redisUtil.setString(RedisKey.getSendlogCodeKey(phoneL),code,300); //并存入redis中 用于判断5分钟内是否过期
        redisUtil.setString(RedisKey.getSendlogCodeInMinKey(phone),code,60); //存入redis中 用于判断每分钟能否再发
        if(!redisUtil.exist(RedisKey.getSendlogCodeInHourKey(phone))){
            redisUtil.setString(RedisKey.getSendlogCodeInHourKey(phone),"0",3600);
        }
        redisUtil.incr(RedisKey.getSendlogCodeInHourKey(phone));
    }

    /**
     * 基本账户修改个人信息和密码
     * @param form
     */
    @Override
    public void updateAccount(AccountUpdateForm form,Long id) {
        Account account = accountMapper.selectById(id);
        if(account==null){
            throw new AccountException(AccountExceptionCode.ACCOUNT_NO_REGISTER);
        }
        if(form.getPhone()!=null && !(form.getPhone().toString().equals(""))){
            QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",form.getPhone());
            Account one = accountMapper.selectOne(queryWrapper);
            if(one!=null){
                throw new AccountException(AccountExceptionCode.ACCOUNT_IS_EXIT);
            }else{
                account.setPhone(form.getPhone());
            }
        }
        if(form.getNickName()!=null && !(form.getNickName().equals(""))){
            account.setNickName(form.getNickName());
        }
        if(form.getPassword()!=null && !(form.getPassword().equals(""))){
            account.setPassword(form.getPassword());
        }
        accountMapper.updateById(account);
    }

    /**
     * 基本账户注册
     * @param form
     * @return
     */
    @Override
    public Account register(AccountRegisterForm form) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",form.getPhone()).or().eq("email",form.getEmail());
        Account account = accountMapper.selectOne(queryWrapper);
        if(account!=null){
            throw new AccountException(AccountExceptionCode.ACCOUNT_IS_EXIT);
        }
        Account newAccount = BeanUtil.toBean(form, Account.class);
        newAccount.setRole("商家");
        accountMapper.insert(newAccount);

        redisUtil.delete(RedisKey.getSendlogCodeKey(form.getPhone()));
        return newAccount;
    }

    /**
     * 注册时检测账号存在性
     * @param form
     */
    @Override
    public String check(AccountCheckForm form) {

        QueryWrapper<Account> queryWrapper = new QueryWrapper<Account>();
        queryWrapper.eq("phone",form.getPhone()).or().eq("email",form.getEmail());
        Account account = accountMapper.selectOne(queryWrapper);
        if(account!=null){
            throw new AccountException(AccountExceptionCode.ACCOUNT_IS_EXIT);
        }
        return null;
    }
}
